package com.smartscreen.authmanage.controller;

import com.smartscreen.authmanage.dto.LoginRequest;
import com.smartscreen.authmanage.dto.LoginResponse;
import com.smartscreen.authmanage.dto.RefreshTokenRequest;
import com.smartscreen.authmanage.dto.RegisterRequest;
import com.smartscreen.authmanage.entity.User;
import com.smartscreen.authmanage.service.AuthService;
import com.smartscreen.common.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    @PostMapping("/register")
    public ApiResponse<LoginResponse> register(@RequestBody RegisterRequest registerRequest) {
        try {
            LoginResponse response = authService.register(registerRequest);
            return ApiResponse.success("注册成功", response);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = authService.login(loginRequest);
            return ApiResponse.success("登录成功", response);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PostMapping("/validate")
    public ApiResponse<Boolean> validateToken(@RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.replace("Bearer ", "");
            Boolean isValid = authService.validateToken(token);
            return ApiResponse.success(isValid);
        } catch (Exception e) {
            return ApiResponse.error("令牌验证失败");
        }
    }
    
    @PostMapping("/refresh")
    public ApiResponse<LoginResponse> refreshToken(@RequestBody RefreshTokenRequest refreshTokenRequest) {
        try {
            LoginResponse response = authService.refreshToken(refreshTokenRequest);
            return ApiResponse.success("令牌刷新成功", response);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @GetMapping("/me")
    public ApiResponse<User> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.replace("Bearer ", "");
            User user = authService.getCurrentUser(token);
            if (user != null) {
                // 不返回密码
                user.setPassword(null);
                return ApiResponse.success(user);
            } else {
                return ApiResponse.error("用户信息获取失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取用户信息失败");
        }
    }
}